package com.yangrong.thread.chapter6;

/**
 * 定义执行线程executeThread，将runner线程设置为执行线程的守护线程
 * 
 * @author YangRong
 * @date 2020年5月26日
 */
public class ThreadService {

	private Thread executeThread;

	private boolean finished = false;

	public void execute(Runnable task) {
		executeThread = new Thread() {
			@Override
			public void run() {
				Thread runner = new Thread(task);
				runner.setDaemon(true);

				runner.start();
				try {
					runner.join();
					finished = true;
				} catch (InterruptedException e) {
//					e.printStackTrace();
					System.out.println("任务超时，结束线程！");
					// ...
				}
			}
		};

		executeThread.start();
	}

	public void shutdown(long mills) {
		long currentTime = System.currentTimeMillis();
		while (!finished) {
			if ((System.currentTimeMillis() - currentTime) >= mills) {
				executeThread.interrupt();
				break;
			}

			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				System.out.println("执行线程被打断。");
				break;
			}
		}

		finished = false;
	}

}
